package com.briup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.briup.bean.Article;
import com.briup.bean.Comment;
import com.briup.bean.Ext.ArticleExt;
import com.briup.bean.User;
import com.briup.mapper.ArticleMapper;
import com.briup.mapper.CommentMapper;
import com.briup.mapper.UserMapper;
import com.briup.mapper.ext.ArticleMapperExt;
import com.briup.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.service.dto.ArticleDTO;
import com.briup.util.BriupBeanUtils;
import com.briup.web.vo.ArticleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author syh
 * @since 2024-09-10
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
    @Autowired
    private ArticleMapper mapper;
    @Autowired
    private ArticleMapperExt mapperExt;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public ArticleExt findById(Integer id) {
        ArticleExt byId = mapperExt.findById(id);
        return byId;
    }

    @Override
    public IPage<ArticleDTO> findByPage(ArticleVO vo) {
        //通过Mybatisplus实现将PO对象转化为DTO对象

        //多表查询： Mybatisplus不支持多表查询(@TableName) ,只能分开查询，将结果组合起来service

        //1.分页多条件查询数据库信息，返回结果封装PO对象

        Page page = new Page<>(vo.getPageNum(), vo.getPageSize());

        //包含文章对象的集合,提供分页查询和查询的条件
        LambdaQueryWrapper<Article> wrapper = Wrappers.lambdaQuery(Article.class).like(Article::getTitle, vo.getTitle());
        IPage<Article> pageInfo = Db.page(page, wrapper);
        //转化后成为文章DTO对象的集合
        List dtoList = pageInfo.getRecords().stream()
                .map(article ->{
                       ArticleDTO dto= BriupBeanUtils.copyBean(article, ArticleDTO.class);
                    //查询文章评论信息
                    LambdaQueryWrapper<Comment> wrapper1 = Wrappers.lambdaQuery(Comment.class).eq(Comment::getArticleId, dto.getId());
                    List<Comment> comments = commentMapper.selectList(wrapper1);
                    dto.setComments(comments);
                    //设置文章作者信息
                    User user = userMapper.selectById(dto.getUserId());
                    dto.setAuthor(user);
                    return dto;
                })
                .collect(Collectors.toList());
        page.setRecords(dtoList);
        return page;
    }


}
